using System.Collections;
using UnityEngine;
using Mirror;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System.IO;

/// <summary>
/// 场景初始化器 - 确保所有关键组件在正确的顺序初始化
/// 添加此组件到场景中最早加载的物体上（如空的GameObject）
/// </summary>
public class SceneInitializer : MonoBehaviour
{
    [Header("组件初始化")]
    [SerializeField] private bool initializeOnStartup = true;
    [SerializeField] private bool ensureNetworkDiscovery = true;
    [SerializeField] private bool ensureWordDatabase = true;
    [SerializeField] private bool ensureRoomManager = true;
    
    [Header("调试设置")]
    [SerializeField] private bool verboseLogging = true;
    
    // 场景名称用于日志标识
    private string sceneName;
    
    private void Awake()
    {
        // 获取当前场景名称用于日志
        sceneName = SceneManager.GetActiveScene().name;
        Debug.Log($"[SceneInitializer] 场景 {sceneName} 初始化开始");
        
        // 确保不被销毁，直到场景切换
        DontDestroyOnLoad(gameObject);
        
        // 注册场景加载事件
        SceneManager.sceneLoaded += OnSceneLoaded;
    }
    
    private void Start()
    {
        if (initializeOnStartup)
        {
            StartCoroutine(InitializeComponents());
        }
    }
    
    private void OnDestroy()
    {
        // 取消事件订阅
        SceneManager.sceneLoaded -= OnSceneLoaded;
    }
    
    private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        Debug.Log($"[SceneInitializer] 场景 {scene.name} 已加载，开始初始化组件");
        StartCoroutine(InitializeComponents());
    }
    
    /// <summary>
    /// 按照正确的顺序初始化所有关键组件
    /// </summary>
    private IEnumerator InitializeComponents()
    {
        Debug.Log($"[SceneInitializer] 开始初始化组件...");
        
        // 等待一帧确保场景完全加载
        yield return null;
        
        // 1. 简化：只确保基本的NetworkManager和SimpleNetworkManager存在
        EnsureNetworkManager();
        yield return null;
        
        // 2. 不再确保RoomDiscovery组件存在
        if (ensureNetworkDiscovery)
        {
            Debug.Log("[SceneInitializer] 跳过确保NetworkDiscovery存在的步骤，该功能已移除");
            yield return null;
        }
        
        // 3. 确保WordDatabase存在
        if (ensureWordDatabase)
        {
            EnsureWordDatabase();
            yield return null;
        }
        
        // 4. 不再确保RoomManager存在
        if (ensureRoomManager)
        {
            Debug.Log("[SceneInitializer] 跳过确保RoomManager存在的步骤，该功能已移除");
            yield return null;
        }
        
        // 5. 处理场景特定的初始化
        yield return StartCoroutine(HandleSceneSpecificInit());
        
        Debug.Log($"[SceneInitializer] 组件初始化完成");
    }
    
    /// <summary>
    /// 确保场景中存在NetworkManager
    /// </summary>
    private void EnsureNetworkManager()
    {
        NetworkManager networkManager = FindObjectOfType<NetworkManager>();
        
        if (networkManager == null)
        {
            Debug.LogWarning("[SceneInitializer] 场景中没有NetworkManager，创建一个新实例");
            GameObject networkManagerObj = new GameObject("NetworkManager");
            networkManager = networkManagerObj.AddComponent<NetworkManager>();
            
            // 添加NetworkManagerHUD组件，这是Mirror自带的UI
            if (networkManager.GetComponent<NetworkManagerHUD>() == null)
            {
                networkManagerObj.AddComponent<NetworkManagerHUD>();
            }
            
            DontDestroyOnLoad(networkManagerObj);
        }
        else if (verboseLogging)
        {
            Debug.Log("[SceneInitializer] NetworkManager已存在");
            
            // 确保有NetworkManagerHUD
            if (networkManager.GetComponent<NetworkManagerHUD>() == null)
            {
                networkManager.gameObject.AddComponent<NetworkManagerHUD>();
                Debug.Log("[SceneInitializer] 添加了NetworkManagerHUD组件");
            }
        }
    }
    
    /// <summary>
    /// 确保WordDatabase存在
    /// </summary>
    private void EnsureWordDatabase()
    {
        if (WordDatabase.Instance == null)
        {
            Debug.LogWarning("[SceneInitializer] 未找到WordDatabase实例，创建一个新实例");
            GameObject wordDBObject = new GameObject("WordDatabase");
            wordDBObject.AddComponent<WordDatabase>();
            DontDestroyOnLoad(wordDBObject);
        }
        else if (verboseLogging)
        {
            Debug.Log("[SceneInitializer] WordDatabase实例已存在");
        }
    }
    
    /// <summary>
    /// 处理场景特定的初始化
    /// </summary>
    private IEnumerator HandleSceneSpecificInit()
    {
        string currentScene = SceneManager.GetActiveScene().name;
        
        // 根据场景名执行特定的初始化
        switch (currentScene.ToLower())
        {
            case "battle":
                yield return StartCoroutine(InitializeBattleScene());
                break;
                
            case "login":
                yield return StartCoroutine(InitializeLoginScene());
                break;
                
            default:
                Debug.Log($"[SceneInitializer] 没有为场景 {currentScene} 定义特殊初始化步骤");
                break;
        }
    }
    
    /// <summary>
    /// 初始化战斗场景
    /// </summary>
    private IEnumerator InitializeBattleScene()
    {
        Debug.Log("[SceneInitializer] 初始化战斗场景...");
        
        // 查找InputManager
        InputManager[] inputManagers = FindObjectsOfType<InputManager>();
        
        if (inputManagers.Length == 0)
        {
            Debug.LogWarning("[SceneInitializer] 战斗场景中未找到InputManager!");
        }
        else
        {
            Debug.Log($"[SceneInitializer] 找到 {inputManagers.Length} 个InputManager实例");
            
            // 查找所有Text组件，包括非激活的
            UnityEngine.UI.Text[] allTexts = FindObjectsOfType<UnityEngine.UI.Text>(true);
            
            if (verboseLogging)
            {
                Debug.Log($"[SceneInitializer] 战斗场景中有 {allTexts.Length} 个Text组件");
                foreach (var text in allTexts)
                {
                    Debug.Log($"  - Text: {text.name}, 内容: '{text.text}', 激活: {text.gameObject.activeInHierarchy}");
                }
            }
        }
        
        // 确保BattleSceneManager存在
        if (FindObjectOfType<BattleSceneManager>() == null)
        {
            Debug.Log("[SceneInitializer] 创建BattleSceneManager");
            GameObject battleManagerObj = new GameObject("BattleSceneManager");
            battleManagerObj.AddComponent<BattleSceneManager>();
        }
        
        yield return null;
    }
    
    /// <summary>
    /// 初始化登录场景
    /// </summary>
    private IEnumerator InitializeLoginScene()
    {
        Debug.Log("[SceneInitializer] 初始化登录场景...");
        
        // 查找Canvas
        Canvas canvas = FindObjectOfType<Canvas>();
        if (canvas != null)
        {
            // 检查是否已存在状态文本
            if (GameObject.Find("StatusText") == null)
            {
                // 创建StatusText游戏对象
                GameObject statusTextObj = new GameObject("StatusText");
                statusTextObj.transform.SetParent(canvas.transform, false);
                
                // 添加RectTransform组件
                RectTransform rectTransform = statusTextObj.AddComponent<RectTransform>();
                rectTransform.anchorMin = new Vector2(0.5f, 0);
                rectTransform.anchorMax = new Vector2(0.5f, 0);
                rectTransform.pivot = new Vector2(0.5f, 0);
                rectTransform.anchoredPosition = new Vector2(0, 20);
                rectTransform.sizeDelta = new Vector2(400, 30);
                
                // 添加Text组件
                Text statusText = statusTextObj.AddComponent<Text>();
                statusText.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
                statusText.fontSize = 18;
                statusText.alignment = TextAnchor.MiddleCenter;
                statusText.color = Color.white;
                statusText.text = "等待导入词库...";
                
                Debug.Log("[SceneInitializer] 创建了状态文本");
            }
            
            // 检查是否已存在文件名文本
            if (GameObject.Find("FileNameText") == null)
            {
                // 创建FileNameText游戏对象
                GameObject fileNameTextObj = new GameObject("FileNameText");
                fileNameTextObj.transform.SetParent(canvas.transform, false);
                
                // 添加RectTransform组件
                RectTransform rectTransform = fileNameTextObj.AddComponent<RectTransform>();
                rectTransform.anchorMin = new Vector2(0.5f, 0);
                rectTransform.anchorMax = new Vector2(0.5f, 0);
                rectTransform.pivot = new Vector2(0.5f, 0);
                rectTransform.anchoredPosition = new Vector2(0, 50); // 位置在StatusText上方
                rectTransform.sizeDelta = new Vector2(400, 30);
                
                // 添加Text组件
                Text fileNameText = fileNameTextObj.AddComponent<Text>();
                fileNameText.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
                fileNameText.fontSize = 18;
                fileNameText.alignment = TextAnchor.MiddleCenter;
                fileNameText.color = new Color(0.2f, 0.6f, 1.0f); // 使用蓝色以区分
                fileNameText.text = "未选择文件";
                
                Debug.Log("[SceneInitializer] 创建了文件名文本");
            }
            
            // 检查是否已存在提示文本
            if (GameObject.Find("LibraryInfoText") == null)
            {
                // 创建LibraryInfoText游戏对象
                GameObject infoTextObj = new GameObject("LibraryInfoText");
                infoTextObj.transform.SetParent(canvas.transform, false);
                
                // 添加RectTransform组件
                RectTransform rectTransform = infoTextObj.AddComponent<RectTransform>();
                rectTransform.anchorMin = new Vector2(0.5f, 1);
                rectTransform.anchorMax = new Vector2(0.5f, 1);
                rectTransform.pivot = new Vector2(0.5f, 1);
                rectTransform.anchoredPosition = new Vector2(0, -20); // 位置在顶部
                rectTransform.sizeDelta = new Vector2(600, 60);
                
                // 添加Text组件
                Text infoText = infoTextObj.AddComponent<Text>();
                infoText.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
                infoText.fontSize = 14;
                infoText.alignment = TextAnchor.MiddleCenter;
                infoText.color = Color.yellow;
                infoText.text = "点击\"导入词库\"按钮可以导入Excel文件。已检测到EPPlus库支持，可以正常使用Excel导入功能。";
                
                Debug.Log("[SceneInitializer] 创建了库信息提示文本");
            }
        }
        else
        {
            Debug.LogWarning("[SceneInitializer] 未找到Canvas，无法创建UI文本");
        }
        
        // 这里可以添加其他登录场景的特殊初始化
        
        // 创建Plugins目录（如果不存在）
        if (!Directory.Exists(Application.dataPath + "/Plugins"))
        {
            Directory.CreateDirectory(Application.dataPath + "/Plugins");
            Debug.Log("[SceneInitializer] 创建了Plugins目录，用于存放ExcelDataReader库");
        }
        
        yield return null;
    }
} 